package com.gym.service.user.impl;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.gym.enums.ResultEnum;
import com.gym.mapper.user.UserRoleMapper;
import com.gym.pojo.user.Role;
import com.gym.pojo.user.UserRole;
import com.gym.pojo.user.UserRoleExample;
import com.gym.service.user.RoleService;
import com.gym.service.user.UserRoleService;

@Service
// @Slf4j
public class UserRoleServiceImpl implements UserRoleService {

	private Logger log = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private UserRoleMapper userRoleMapper;

	@Autowired
	private RoleService roleService;

	@Override
	public void addUserRole(UserRole userRole) {
		this.userRoleMapper.insertSelective(userRole);
	}

	@Override
	public ResultEnum deleteUserRole(Long userId) {
		try {
			UserRoleExample userRoleExample = new UserRoleExample();
			UserRoleExample.Criteria criteria = userRoleExample
					.createCriteria();
			criteria.andUserIdEqualTo(userId);
			this.userRoleMapper.deleteByExample(userRoleExample);
		} catch (Exception e) {
			log.error("UserRoleServiceImpl-deleteUserRole出现未知异常："
					+ e.getMessage());
			return ResultEnum.UNKNOW_EXCEPTION;
		}
		return ResultEnum.SUCCESS;
	}

	@Override
	public ResultEnum updateUserRole(UserRole userRole) {
		try {
			UserRoleExample userRoleExample = new UserRoleExample();
			UserRoleExample.Criteria criteria = userRoleExample
					.createCriteria();
			criteria.andUserIdEqualTo(userRole.getUserId());
			this.userRoleMapper.updateByExample(userRole, userRoleExample);
			return ResultEnum.SUCCESS;
		} catch (Exception e) {
			log.error("UserRoleServiceImpl-updateUserRole出现未知异常："
					+ e.getMessage());
			return ResultEnum.UNKNOW_EXCEPTION;
		}

	}

	@Override
	public List<UserRole> userRoles(Long userId) {
		UserRoleExample userRoleExample = new UserRoleExample();
		UserRoleExample.Criteria criteria = userRoleExample.createCriteria();
		criteria.andUserIdEqualTo(userId);
		return userRoleMapper.selectByExample(userRoleExample);
	}

	@Override
	public Set roleNames(Long userId) {
		Set<String> roles = new HashSet<String>();
		List<UserRole> userRoles = userRoles(userId);
		for (UserRole userRole : userRoles) {
			Role role = roleService.getById(userRole.getRoleId());
			roles.add(role.getRoleName());
		}
		return roles;
	}
}
